/*
 * Copyright (c) 2006 - 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import java.util.concurrent.TimeUnit;

/**
 * <p>Project: app2022 - T17
 * <p>Powered by webrx On 2022-02-07 14:31:57
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class T17 {
    Object lock = new Object();

    public static void main(String[] args) {
        var ex = new T17();
        new Thread(ex::work, "T1").start();
        new Thread(ex::work, "T2").start();
        new Thread(ex::work, "T3").start();
        new Thread(ex::work, "T4").start();
        new Thread(ex::work, "ok").start();
    }


    void work() {
        String tn = Thread.currentThread().getName();
        System.out.println(tn + "线程启动");
        if ("ok".equals(tn)) {
            try {
                TimeUnit.SECONDS.sleep(2);
                synchronized (lock) {
                    lock.notifyAll();//推荐使用
                    //lock.notify();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            for (int i = 0; i < 3; i++) {
                System.out.printf("%s = %d%n", tn, i);
                synchronized (lock) {
                    try {
                        if (i < 1) {
                            System.out.println(tn + "wait()....");
                            lock.wait(); //没有唤醒   notify()
                        }
                        //TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        System.out.println(tn + "线程结束...");
    }
}
